package files;

import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: Jaan Sepp
 * Date: 20.09.11
 * Time: 21:00
 * To change this template use File | Settings | File Templates.
 */
public class FileHelper {

  private static org.apache.log4j.Logger log = utils.Logger.getInstance(FileHelper.class.getName());

  public String readFromFile(String filePathAndName) {
    String fileContents = "";
    String temp;
    try {
      FileReader fileReader = new FileReader(filePathAndName);
      BufferedReader br = new BufferedReader(fileReader);
      while ((temp = br.readLine()) != null) {
        fileContents += temp + "\n";
      }
      br.close();
    } catch (FileNotFoundException e) {
      log.warn("File " + filePathAndName + " not found");
    } catch (IOException e) {
      log.warn("Unable to read from file: " + filePathAndName + ".");
    }
    return fileContents;
  }

  public void writeToFile(String filePathAndName, String contents) {
    String fileName = filePathAndName;
    File file = new File(fileName);
    if (file.exists()) {
      writeContents(contents, fileName);
    } else {
      createFile(file);
      writeContents(contents, fileName);
    }
  }

  public void createFile(File file) {
    try {
      file.createNewFile();
      System.out.println("New file " + file.getName() + " has been created to the current directory");
    } catch (Exception e) {
      System.out.println("Unable to create file " + file.getName() + ".");
    }
  }

  private void writeContents(String contents, String fileName) {
    try {
      FileWriter fileWriter = new FileWriter(fileName);
      BufferedWriter bw = new BufferedWriter(fileWriter);
      bw.write(contents);
      bw.flush();
      bw.close();
    } catch (IOException e) {
      log.warn("Unable to write to file: " + fileName + ". " + e.getMessage());
    }
  }
}
